<template>
  <div class="login">
    <div class="login-box rounded">
      <div v-if="isShow == 1" class="container p-4">
        <h3 class="pt-4 pb-2">登录</h3>
        <div @click="isShow = 2" class="main1 pb-2">
          没有账号？立即注册
        </div>
        <div class="main2">
          <div> <input v-model="loginUser.loginAcc" class="inp" type="text" placeholder="请输入账号"></div>
          <div><input v-model="loginUser.loginPwd" class="inp" type="password" placeholder="请输入密码"></div>
        </div>

        <div class="text-center">
          <button @click="loginFn" class="btn w-50 rounded-pill  text-light">登录</button>
        </div>
      </div>
      <div v-else class="container p-4">
        <h3 class="pt-4 pb-2">注册</h3>
        <div @click="isShow = 1" class="main1 pb-2">
          已有账号？立即登录
        </div>
        <div class="main2">
          <div> <input v-model="userForm.account" class="inp" type="text" placeholder="请输入账号，至少包括字母与数字"></div>
          <div> <input v-model="userForm.username" class="inp" type="text" placeholder="请输入用户名"></div>
          <div> <input v-model="userForm.password" class="inp" type="password" placeholder="请输入密码，至少包括大小写字母与数字"></div>
          <div> <input v-model="userForm.password2" class="inp" type="password" placeholder="请输入确认密码"></div>
          <!-- 上传图片 -->
          <div>
            <label class="mb-1" for="formFileLg">上传头像</label>
            <input @change="chooseImage" id="formFileLg" type="file">
          </div>
          <div>
            <img v-if="preview" style="width: 100px;" :src="preview" alt="图片预览">
          </div>
        </div>
        <div class="text-center">
          <button @click="registerFn" class="btn w-50 rounded-pill  text-light">注册</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { uploadPhoto, register, login, logined } from "@/api/index";
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus'
import { useCounterStore } from "@/stores/counter";
const counter = useCounterStore();
// interface IData {
//   [key: string]: string | number | undefined | any
// }

interface IUser {
  account: string
  password: string
  password2: string
  username: string
  imgUrl: string
}
interface loginUser {
  loginAcc: string
  loginPwd: string
}


// 登录表单
const loginUser = reactive<loginUser>({
  loginAcc: "",
  loginPwd: ""
})

// 注册表单
const userForm = reactive<IUser>({
  account: "",
  password: "",
  password2: "",
  username: "",
  imgUrl: ""
})

const isShow = ref<number>(1);

const file = ref<File | null>(null);
// 图片预览
const preview = ref<string>();
let imgUrl = "";
const router = useRouter()

const chooseImage = (event: Event) => {
  const target = event.target as HTMLInputElement;
  file.value = target.files?.[0] ?? null;

  if (file.value) {
    // 创建 FileReader 实例用于读取文件
    const reader = new FileReader();
    // 监听文件加载完成事件
    reader.addEventListener(
      "load",
      () => {
        // 将读取到的 base64 数据赋值给 preview 用于图片预览
        preview.value = reader.result as string;
      },
      false
    );
    // 将图像文件转换为 Base64 字符串
    reader.readAsDataURL(file.value);
  }
};

// 注册
const registerFn = async () => {
  if (file.value) {
    const formData = new FormData();
    formData.append("photo", file.value);
    await uploadPhoto(formData)
      .then(
        (resDate) => {
          // console.log(resDate);
          if (resDate.data.code === 200) {
            imgUrl = resDate.data.picUrl;
          }
        }
      )
  }
  // console.log(imgUrl);
  const { account, password, password2, username } = userForm;
  if (account == '' || password == '' || password2 == '' || username == '') {
    ElMessage({
      showClose: true,
      message: '请填写完整信息哦~~',
      type: 'warning',
      offset: 100,
      plain: true,
    })
    return false
  }
  if (password != password2) {
    ElMessage({
      message: '密码不一致~~',
      type: 'warning',
      plain: true,
      offset: 100
    })
    return false
  }
  await register({ account, password, username, imgUrl }).then(
    (resData) => {
      // console.log(resData.data);
      if (resData.data.code == 200) {
        // localStorage.setItem("ID", resData.data.id);
        ElMessage({
          message: '注册成功,请登录~~',
          type: 'success',
          plain: true,
          offset: 100
        })
        isShow.value = 1;
      } else {
        ElMessage({
          message: resData.data.msg,
          type: 'error',
          plain: true,
          offset: 100
        })
      }
    },
    (err) => {
      console.log(err);
      ElMessage({
        message: err.response.data.msg,
        type: 'error',
        plain: true,
        offset: 100
      })
    }
  )

}

// 登录
const loginFn = async () => {
  const { loginAcc, loginPwd } = loginUser;
  if (loginAcc == '' || loginPwd == '') {
    ElMessage({
      message: '请填写完整信息哦~~',
      type: 'warning',
      plain: true,
      offset: 100
    })
    return false
  }
  await login({ account: loginAcc, password: loginPwd })
    .then(
      (resData) => {
        if (resData.data.code == 200) {
          ElMessage({
            message: '登录成功~~',
            type: 'success',
            plain: true,
            offset: 100
          })
          // console.log("用户登录后的数据", resData.data);
          localStorage.setItem("TTOO", resData.data.token);
          const obj = {
            id: resData.data.id,
            username: resData.data.username,
            account: resData.data.account,
            imgUrl: resData.data.imgUrl,
            token: resData.data.token,
            tag: resData.data.tag,
            gender: resData.data.gender,
            createAt: resData.data.createAt,
          }
          counter.userData = obj;
          // console.log("用户登录后的数据", resData.data);
          // localStorage.setItem("USERDATA", JSON.stringify(resData.data))
          setTimeout(() => {
            router.push('/user');
          }, 1000)
        } else {
          ElMessage({
            message: '账号或密码错误~~',
            type: 'error',
            plain: true,
            offset: 100
          })
        }
        // console.log(resData);
      },
      err => {
        ElMessage({
          message: '登录失败~~',
          type: 'error',
          plain: true,
          offset: 100
        })
        console.log(err);
      }
    )
}

const loginedFn = async () => {
  const token = localStorage.getItem("TTOO");
  await logined({ token }).then(
    (resData) => {
      // console.log(resData.data);
      if (resData.data.code == 200) {
        ElMessage({
          message: '你已经登录啦~~',
          type: 'success',
          plain: true,
          offset: 100
        })
      }
    },
    (err) => {
      console.log(err);
    }
  )
}
loginedFn()

</script>

<style lang="less" scoped>
@import "../static/css/common.less";

@media (max-width: 376px) {
  .login {
    .login-box {
      width: 300px !important;
    }
  }
}

body {
  width: 100%;
  height: 100%;
}

.login {
  width: 100%;
  height: 100%;
  background-image: url(../static/imgs/images/loginbg.jpg);
  background-size: cover;
  box-sizing: border-box;
  overflow: hidden;

  .login-box {
    overflow: hidden;

    width: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);

    .main1 {
      color: @grey-color;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        color: rgb(244, 77, 77)
      }
    }

    .main2 {

      .inp {
        width: 100%;
        background-color: transparent;
        border: none;
        border-bottom: 1px solid #ccc;
        margin: 10px 0;
        outline: none;
        font-size: 13px;

        &::-webkit-input-placeholder {
          color: #8f8d8d;
        }
      }
    }

    .btn {
      background-color: rgb(25, 154, 234);
      margin-top: 20px;
    }
  }
}

@media (max-width: 376px) {
  .login-box {
    width: 300px !important;
  }
}
</style>
